<?php

namespace App\Http\Controllers\Backend;

use App\Models\Area;
use App\Models\City;
use App\Models\FoodType;
use App\Models\Province;
use App\Models\School;
use App\Models\UserRole;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use App\Http\Resources\MenuResource;
use App\Models\Permission;

/**
 * Class DataController
 * @package App\Http\Controllers\Backend
 */
class DataController extends BackendController
{
    /**
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $sources = $request->get('sources', []);
        $data = [];
        foreach ($sources as $v) {
            if (method_exists($this, $v)) {
                $data[$v] = call_user_func([$this, $v], $request);
            }
        }
        return $data;
    }

    /**
     * @param Request $request
     * @return Province[]|\Illuminate\Database\Eloquent\Collection
     * 地区
     */
    public function areas(Request $request)
    {
        $id = $request->get("area_id");
        if (!$id) {
            return Province::all();
        } else {
            $cities = City::where("provinceid", $id)->get();
            if (sizeof($cities) > 0) {
                return $cities;
            } else {
                return Area::where("cityid", $id)->get();
            }
        }
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function schools(Request $request)
    {
        return School::isActive()->select(["name",'id'])->get();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function userRoles(Request $request)
    {
        return UserRole::select(['id', 'name'])->get();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function roles(Request $request)
    {
        return Role::where('guard_name','school')->get();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function backendRoles(Request $request)
    {
        return Role::where('guard_name','backend')->get();
    }

    /**
     * @param Request $request
     * @return MenuResource
     */
    public function menus(Request $request)
    {
        return new MenuResource(Permission::backend()->get());
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function foodTypes(Request $request)
    {
        return FoodType::select(['id', 'name'])->get();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     * 根据学校id更换用户角色
     */
    public function getSchoolUserRoles(Request $request)
    {
        return UserRole::query()->where('school_id', $request->school_id)->select(['id', 'name'])->get();
    }
}
